; $(window).on("load", function () {
    $(function () {


        //倒计时
        $(function () {


            setInterval(function () {
                $(".countdown").each(function () {
                    var obj = $(this);
                    // var endTime = new Date(parseInt(obj.attr('value')) * 1000);
                    var endTime = new Date(2019, 7, 10, 17, 00, 00);
                    var nowTime = new Date();
                    var nMS = endTime.getTime() - nowTime.getTime();
                    var myD = Math.floor(nMS / (1000 * 60 * 60 * 24)); //天 
                    var myH = Math.floor(nMS / (1000 * 60 * 60)) % 24; //小时 
                    var myM = Math.floor(nMS / (1000 * 60)) % 60; //分钟 
                    var myS = Math.floor(nMS / 1000) % 60; //秒 
                    var myMS = Math.floor(nMS / 100) % 1; //拆分秒 
                    if (myD >= 0) {
                        var str = myD + "天" + myH + "小时" + myM + "分" + myS + "秒";
                    } else {
                        var str = "已结束！";
                    }
                    obj.html(str);
                });
            }, 100);
        });

        //税费详情
        $(".over-picebox").on("mouseenter", function () {
            $(".view-taxMoreNotice").show();
        });
        $(".over-picebox,.view-taxMoreNotice").on("mouseleave", function () {
            $(".view-taxMoreNotice").hide();
        });
        //返贝壳详情
        $(".view-ReturnInfo").on("mouseenter", function () {
            $(".view-ReturnMoreInfo").show();
        }).on("mouseleave", function () {
            $(".view-ReturnMoreInfo").hide();
        })
        //选择颜色
        $(".attr-values li").on("click", function (e) {
            var index = $(this).index();
            $(".view-SkuSelectItemValue").find("a").eq(index).addClass("current").parent("li").siblings("li").children("a").removeClass("current");
            //如果选中再点击则取消样式
            if (e.target.className == "current") {
                $(this).find("a").removeClass("current");
            }
            if (e.target.innerText == "紫色") {
                $(".bigImg").attr("src", "../images/biglzlv3.jpg")
                $(".middle-img").attr("src", "../images/biglzlv3.jpg");
            } else {
                $(".bigImg").attr("src", "../images/biglzlv1.jpg");
                $(".middle-img").attr({
                    "src": "../images/biglzlv1.jpg"
                });
            }
        })






        //侧边导航栏
        // 购物车
        $("#sidebar-cart").on("mouseenter", function () {
            $(".side-panel-item-cart").show();
        });
        //移出购物车列表隐藏
        $("#sidebar-cart,.side-panel-item-cart").on("mouseleave", function () {
            $(".side-panel-item-cart").hide();
        });
        // 移入手机选项，跳出app二维码
        $(".side-panel-App").on("mouseenter", function () {
            $(".side-panel-phone").show();
        });
        // 移出手机隐藏
        $(".side-panel-App,.side-panel-phone").on("mouseleave", function () {
            $(".side-panel-phone").hide();
        })
        //移到客服图标变文字
        $("#kfzx").on("mouseenter", function () {
            $(".icon-kefu").hide();
            $(".tip-txt").show();
        })
        $("#kfzx").on("mouseleave", function () {
            $(".tip-txt").hide();
            $(".icon-kefu ").show();
        });
        // 回顶上
        $("#elevator").on("mouseenter", function () {
            $(".icon-top").hide();
            $(".top-txt").show();
        })
        $("#elevator").on("mouseleave", function () {
            $(".top-txt").hide();
            $(".icon-top").show();
        })
        //点击回到顶上到最上面
        $("#elevator").on("click", function () {
            $("html").animate({ scrollTop: 0 }, 500);
            return false;
        })
        // 侧边购物车渲染
        async function show() {
            var result = await $.get("../../api/getcarts", {
                uid: JSON.parse($.cookie("userinfo") || "[]").uId,
            })
            num = result.length;
            if (result.length == 0) {
                $(".empty-cart").show();
                $(".carlis").hide();
            } else {
                $(".empty-cart").hide();
                $(".carlis").show();
                window.localStorage.setItem("shopcars1", JSON.stringify(result))
                var sidecart2=``;
                result.forEach(el => {
                   sidecart2 += `
                <li class="carlis" wg-view="item" style="display: list-item; padding: 12px; list-style: none; position: relative; overflow: hidden; height: 60px; border-bottom: none;"><a href="//www.beibei.com/detail/200433472-11353645.html" wg-view="imglink" op-value="itemLink" op-attr="href"><img wg-view="img" op-value="imgUrl" op-attr="src" src="${el.pImg}" style="border: 2px solid rgb(204, 204, 204); background: rgb(255, 255, 255); padding: 2px; width: 50px; height: 50px; position: relative; z-index: 4;"></a><a href="//www.beibei.com/detail/200433472-11353645.html" wg-view="name" op-value="title,itemLink" op-attr="*,href" style="position: absolute; left: 0px; top: 15px; padding: 0px 10px 0px 80px; line-height: 1.2em; height: 30px; overflow: hidden; font-size: 13px; margin: 0px; width: 50%; z-index: 3;">${el.pName}SPF25/PA++30ml</a><p wg-view="sku" op-value="sku_props" style="position: absolute; color: rgb(170, 170, 170); left: 0px; top: 52px; padding: 0px 10px 0px 80px; line-height: 1.2em; height: 14px; overflow: hidden; font-size: 12px; margin: 0px; width: 50%;">颜色:${el.pSize}</p><p wg-view="price" op-value="price" style="position: absolute; color: rgb(255, 84, 130); right: 15px; top: 25px; overflow: hidden; font-size: 16px; padding-left: 80px; margin: 0px; width: 30%; line-height: 1em; text-align: right;">¥${el.pPrice}<br><span wg-view="num" style="display: inline; color: rgb(136, 136, 136); font-size: 13px;"> x${el.pNum}</span></p></li>
                   `
                    //加减
                })
                $(".cartInfor2").append(sidecart2);
                //取出购物车对象,循环,计算总价
                let shopcarts = JSON.parse(window.localStorage.getItem("shopcars1"));
                var shopcartsTotalPrice = 0;
                shopcarts.map((item) => {
                    shopcartsTotalPrice += item.pNum * parseInt(item.pPrice)
                })
            }
            $(".headcarT").text(shopcartsTotalPrice)
            $(".goodnum").text(num)
            console.log(num)
        }
        show()
        //加减
        $('.inputNum').spinner({});
        $(".buy-type").click(function () {
            var num = $(".inputNum").val();
        })

        //手机购买移入出现二维码
        $(".mobile-buy").on("mouseenter", function () {
            $(".canvas").show();
        }).on("mouseleave", function () {
            $(".canvas").hide();
        })
        //点击继续购物后按钮消失
        $(".continue-buy-btn").on("click", function () {
            $(this).hide();
        })

        //锚点跳转
        $(".nav-menu").find("li").on("click", function () {
            $(this).addClass("current").siblings("li").removeClass("current");
        })
        // 商品详情
        $(".nav-menu").find("li").eq(0).on("click", function () {
            $("html,body").animate({ scrollTop: $(".table").offset().top }, 500)
        });
        // 买家口碑
        $(".nav-menu").find("li").eq(1).on("click", function () {
            $("html,body").animate({ scrollTop: $(".con2-mj").offset().top - 80 }, 500)
        });
        // 常见问题
        $(".nav-menu").find("li").eq(2).on("click", function () {
            $("html,body").animate({ scrollTop: $(".con2-que").offset().top - 80 }, 500)
        })
        // 贝贝优势
        $(".nav-menu").find("li").eq(3).on("click", function () {
            $("html,body").animate({ scrollTop: $(".con2-good").offset().top - 70 }, 500)
        })

        //固定导航栏
        $(document).on("scroll", function () {
            var goods_h = $(".detail-meta").height();
            var mH = $(this).scrollTop();
            if (mH > goods_h + 250) {
                $(".nav-bar").css({
                    "position": "fixed"
                });
                $(".main-content").css({
                    "marginTop": $(".nav-bar").height()
                })
            } else {
                $(".nav-bar").css({
                    "position": "absolute"
                });
                $(".main-content").css({
                    "marginTop": 0
                })
            }
        })
        //定义一个全局变量来接受商品的ajax
        var golbaObj = null;
        //渲染数据
        function load() {
            if (window.location.search.indexOf("?") == -1 || window.location.search.indexOf("=") == -1) {
                return;
            }
            $.get(
                "../../api/goods" + window.location.search, function (data) {
                    console.log(data[0]);
                    golbaObj = data[0];
                    //遍历数据插入
                    //中图
                    var midImgHtml =
                        ` <img src="${data[0].big_img[0]}" alt="biglzlv1.jpg" class="middle-img">
                      `;
                    $(".mildBox").append(midImgHtml);
                    //大图
                    var bigImgHtml = `<img src="${data[0].big_img[0]}" alt="biglzlv1.jpg" class="bigImg">`
                    $(".bigimgBox").append(bigImgHtml);
                    // 小图遍历
                    data[0].sm_img.forEach(el => {
                        // < !--小小区域 -->
                        var smImgHtml = `
                        <li class="List1111">
                                <div class="Goods_smImg">
                                    <a href="javascript:;;">
                                        <img src="${el}" a lt="" width="53px"
                                            style="visibility: visible; opacity: 1;" class="clImg">
                                    </a>
                                </div>
                            </li>`
                        $(".Goods_thums").append(smImgHtml)
                    })
                    //给小图绑定移入切换图片事件
                    $(".List1111").on("mouseenter", function () {
                        var index = $(this).index();
                        //中图遍历
                        $(".carousel-wrapper").find("img.middle-img").attr("src",  data[0].big_img[index]);
                        //    选择边框样式
                        $(this).addClass("active").siblings("li").removeClass("active");
                        //大图遍历
                        $(".bigImg").attr("src", data[0].middle_img[index])

                    });

                    //   商品信息渲染
                    //默认li第一个选中
                    $(".List1111").eq(0).addClass("active");
                    fangdaj();
                    $(".navTle").text(data[0].pName);
                    $(".over-jake").attr("src",  data[0].contyImg[0]);
                    $(".over-countyEn").text(data[0].contyEng);
                    $(".over-county").text(data[0].contyTxt);
                    $(".goods-title").text(data[0].pName);
                    $(".over-memo").text(data[0].introduce);
                    //价格
                    $(".price").text(data[0].pirce);
                    $(".oldP").text(data[0].originP);
                    $(".taxpice").text(data[0].taxP);
                    //颜色遍历
                    data[0].color.forEach((el, index) => {
                        var colorHtml = `
                    <li class="view-SkuSelectItemValue colos-item">
                    <a href="javascript:;;">
                        <div class="thumb-box">
                            <img src="${data[0].sm_img[index + 1]}" alt="lv" height="25"
                                width="25">
                        </div>
                        <span class="color">${el}</span>
                    </a>
                </li>
                    `
                        $(".colors").append(colorHtml);
                        $(".colos-item").find("a").on("click", function () {
                            var index = $(this).index();
                            $(this).addClass("current").parent("li").siblings("li").children("a").removeClass("current");

                        })
                        $(".colos-item").eq(0).on("click", function () {
                            $(".middle-img").attr("src",  data[0].big_img[0]);

                        })
                        $(".colos-item").eq(1).on("click", function () {
                            $(".middle-img").attr("src",   data[0].big_img[2]);
                        })
                    })
                },

            )
        }
        load();
        // 放大镜特效
        function fangdaj() {
            //隐藏首页固定的导航
            //放大镜
            // 小区域
            var $smallarea = $(".smallarea");//小区域
            var $middleimg = $(".middle-img");//中图
            var $bigarea = $(".bigarea");//大区域
            var $bigimgBox = $(".bigimgBox")//大图;

            $smallarea.width(($middleimg.width() / $bigimgBox.width()) * $bigarea.width());
            $smallarea.height(($middleimg.width() / $bigimgBox.width()) * $bigarea.width());
            //进入中图,让小区域大区域显示
            $(".carousel-wrapper").on("mouseenter", $middleimg, function () {
                $smallarea.show();
                $bigarea.show();
            })
            $(".carousel-wrapper").on("mousemove", $middleimg, function (e) {
                var x = e.pageX;
                var y = e.pageY;
                var moveX = x - $(this).offset().left - $smallarea.width() / 1.5;
                var moveY = y - $(this).offset().top - $smallarea.height() / 2;
                if (moveX <= 0) {
                    moveX = 0;
                } else if (moveX >= $middleimg.width() - $smallarea.width()) {
                    moveX = $middleimg.width() - $smallarea.width();
                };
                if (moveY <= 0) {
                    moveY = 0;
                } else if (moveY >= $middleimg.height() - $smallarea.height()) {
                    moveY = $middleimg.height() - $smallarea.height();
                };

                var scale = $bigarea.height() / $smallarea.height();
                $bigimgBox.css({
                    left: -scale * moveX,
                    top: -scale * moveY
                });
                $smallarea.css({
                    left: moveX,
                    top: moveY
                })
            })
            $(".smallarea").on("mouseleave", function () {
                $smallarea.hide();
                $bigarea.hide();
            })
        }
        //点击的时候把选择的规格颜色记录到当前全局变量里
        $(".colors").on("click", ".colos-item", function () {
            golbaObj.sizeStyle = $(this).find(".color").text();
            golbaObj.seleImg = $(this).find("img").attr("src");
        })

        var startTop = 0;
        var startLeft = 0;

        //resize窗口改变事件
        $(window).resize(function () {
            // offset = $("#sidebar-cart").offset();
            offset = $("#sidebar-cart").offset();
            startTop = $(this).scrollTop();
            startLeft = $(this).scrollLeft();
        });
        //滚动条事件
        $(window).on("scroll", function () {
            offset = $("#sidebar-cart").offset();
            startTop = $(this).scrollTop();
            startLeft = $(this).scrollLeft();
        })

        function sideClick() {
            let user2 = JSON.parse(($.cookie("userinfo")) || "{}");
            $(".side-panel").on("click",".side-panel-item-wrap,.tocarts",function () {
                console.log(1111)
                $.ajax({
                    url: "../../api/login",
                    data: {
                        uname: user2.uname,
                        upwd: user2.upwd
                    },
                    type: "post",
                    dataType: "json"
                }).done((data=>{
                if (data.status == -1) {
                    console.log(11111)
                    layer.confirm("你还没有登录",{
                        btn:["去","不去"]
                    },
                    (index)=>{
                        layer.close(index);
                        window.location="./login.html"
                    },
                    (index)=>{
                        layer.close(index);
                        return
                    }
                    )
                }else{
                    window.location="./shopcar.html"
                }
                }))
            })
        }
        sideClick()


        //加入购物车获取到数据
        $("body").on("click", ".buy-type", function () {
            //登录才能进入购物车
            let user2 = JSON.parse(($.cookie("userinfo")) || "{}");
            $.ajax({
                url: "../../api/login",
                data: {
                    uname: user2.uname,
                    upwd: user2.upwd
                },
                type: "post",
                dataType: "json"
            }).then((data) => {
                if (data.status == -1) {
                    layer.confirm("你还没有登录",{
                        btn:["去","不去"]
                    },
                    (index)=>{
                        layer.close(index);
                        window.location="./login.html"
                    },
                    (index)=>{
                        layer.close(index);
                        return
                    }
                    )
                }else{
                    //判断是否选择了规格颜色
            if (golbaObj.sizeStyle == undefined) {
                layer.msg("你还没有选择颜色~", () => {
                    time: 2000;
                })
                return;
            }
            var addcar = $(this);
            var img = addcar.parents(".ops").prev().prev().children(".attr").children(".attr-values").children(".view-SkuSelectItemValue").children("a.current").find("img").attr("src");
            var flyer = $('<img class="u-flyer" src="' + img + '">');
            // if(flyer){}
            //飞
            flyer.fly({
                //起点
                start: {
                    left: $(".addCartText").offset().left,
                    top: $(".addCartText").offset().top - startTop
                },
                //终点
                end: {
                    left: $("#sidebar-cart").offset().left - startLeft,
                    top: $("#sidebar-cart").offset().top - startTop,
                    width: 0,
                    height: 0
                },
                //到达终点调用
                onEnd: function () {
                    console.log("到达终点");
                    $(".continue-buy-btn").show();
                    flyer.remove();
                }
            })
            $.cookie("cartInfo", JSON.stringify(golbaObj) || "{}");
            var saveObj = {
                uid: JSON.parse(($.cookie("userinfo")) || "{}").uId,
                pid: golbaObj.pid,
                pName: golbaObj.pName,
                pPrice: golbaObj.pirce,
                pNum: $(".inputNum").val(),
                pTotal: golbaObj.pirce * $(".inputNum").val(),
                pImg: golbaObj.seleImg,
                pSize: golbaObj.sizeStyle
            }
            console.log(saveObj)
            $.ajax({
                url: "../../api/addCart",
                type: "post",
                data: saveObj,
                dataType: "json"
            }).done((data) => {
                console.log(data)
            })
                }
            })
            
        });

    })
})